{% extends 'base.html' %}
{% load static %}
{% block content %}
    <div class="page-holder">

      <div class="container">
        <!-- HERO SECTION-->

        <section class="py-5">
          <h2 class="h5 text-uppercase mb-4">购物车</h2>
          <div class="row">
            <div class="col-lg-8 mb-4 mb-lg-0">
              <!-- CART TABLE-->
              <div class="table-responsive mb-4" style="height: 400px">
                <table class="table text-nowrap">
                  <thead class="bg-light">
                    <tr>
                      <th class="border-0 p-3" scope="col"> <strong class="text-sm text-uppercase">产品</strong></th>
                      <th class="border-0 p-3" scope="col"> <strong class="text-sm text-uppercase">价格</strong></th>
                      <th class="border-0 p-3" scope="col"> <strong class="text-sm text-uppercase">数量</strong></th>
                      <th class="border-0 p-3" scope="col"> <strong class="text-sm text-uppercase">合计</strong></th>
                      <th class="border-0 p-3" scope="col"> <strong class="text-sm text-uppercase"></strong></th>
                    </tr>
                  </thead>
                  <tbody class="border-0">
                  {% for cart in cart_list %}
                    <tr>
                      <th class="ps-0 py-3 border-light" scope="row">
                        <div class="d-flex align-items-center"><a class="reset-anchor d-block animsition-link" href="/detail/{{ cart.id }}/"><img src="/{{ cart.goods_img }}" alt="..." style="width:60px;height: 60px;"/></a>
                          <div class="ms-3"><strong class="h6"><a class="reset-anchor animsition-link" href="detail.html">{{ cart.goods_name }}</a></strong></div>
                        </div>
                      </th>
                      <td class="p-3 align-middle border-light">
                        <p class="mb-0 small productPrice" data-price="{{ cart.goods_price }}" >${{ cart.goods_price }}</p>
                      </td>
                      <td class="p-3 align-middle border-light">

<div class="border d-flex align-items-center justify-content-between px-3"><span class="small text-uppercase text-gray headings-font-family">数量</span>

<div class="quantity d-flex align-items-center">
    <button class="dec-btn btn btn-secondary p-0" onclick="decrementQuantity(this)" data-product-id='{{ cart.id }}'>
        <i class="fas fa-caret-left"></i>
    </button>
{#    <label for="quantityInput" class="some-class-if-needed"></label>#}
    <input class="form-control form-control-sm border-0 shadow-none text-center p-0 quantityInput" type="text" value="{{ cart.number }}" id="quantityInput">

    <button class="inc-btn btn btn-secondary p-0" onclick="incrementQuantity(this)" data-product-id='{{ cart.id }}'>
        <i class="fas fa-caret-right"></i>
    </button>
</div>

</div>
                      </td>
                      <td class="p-3 align-middle border-light">
                        <p class="mb-0 small totalPrice">$</p>
                      </td>
                      <td class="p-3 align-middle border-light"><a class="reset-anchor" href="/cart/deletecart/{{ cart.id }}/"><i class="fas fa-trash-alt small text-muted"></i></a></td>
                    </tr>
                    {% endfor %}
                  </tbody>
                </table>
              </div>
              <!-- CART NAV-->
              <div class="bg-light px-4 py-3">
                <div class="row align-items-center text-center">
                  <div class="col-md-6 mb-3 mb-md-0 text-md-start"><a class="btn btn-link p-0 text-dark btn-sm" href="/shop/"><i class="fas fa-long-arrow-alt-left me-2"> </i>继续购物</a></div>
                  <div class="col-md-6 text-md-end"><a class="btn btn-outline-dark btn-sm" href="/order/checkout/">前往结算<i class="fas fa-long-arrow-alt-right ms-2"></i></a></div>
                </div>
              </div>
            </div>
            <!-- ORDER TOTAL-->
            <div class="col-lg-4">
              <div class="card border-0 rounded-0 p-lg-4 bg-light"style="width: 500px;height: 490px;">
                <div class="card-body">
                  <h5 class="text-uppercase mb-4">购物车总数</h5>
                  <ul class="list-unstyled mb-0">
                    <li class="d-flex align-items-center justify-content-between"><strong class="text-uppercase small font-weight-bold">小计</strong><span class="text-muted small">${{ num }}</span></li>
                    <li class="border-bottom my-2"></li>
                    <li class="d-flex align-items-center justify-content-between mb-4"><strong class="text-uppercase small font-weight-bold">合计</strong><span>${{ sum }}</span></li>
                    <li>
                      <form action="#">
                        <div class="input-group mb-0">
<!--                          <input class="form-control" type="text" placeholder="输入你的优惠券">-->
<!--                          <button class="btn btn-dark btn-sm w-100" type="submit"> <i class="fas fa-gift me-2"></i>申请优惠券</button>-->
                        </div>
                      </form>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
{% endblock %}

{% block footer %}
<script src="{% static  '/vendor/bootstrap/js/bootstrap.bundle.js' %}"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 获取价格和数量
    {#var priceElement = document.querySelector('.productPrice');#}
    var priceElement = document.getElementsByClassName("productPrice")
    var quantityElement = document.getElementsByClassName('quantityInput');
    var totalPriceElement = document.getElementsByClassName('totalPrice');

    console.log(111)
    console.log('priceElement.length:'+priceElement.length)

    for(var i=0;i<priceElement.length;i++) {
        var price = parseFloat(priceElement[i].getAttribute('data-price')); // 使用data属性获取价格，因为它不会因用户输入而改变
        var quantity = parseInt(quantityElement[i].value, 10); // 假设输入是整数
        // 计算总价
        var totalPrice = price * quantity;
        console.log('totalPrice:'+totalPrice)
             // 更新页面上的总价显示

        totalPriceElement[i].innerText  = '$' + totalPrice.toFixed(2); // 保留两位小数



    }


});


    // 在 Django 模板中，你可以直接从 CSRF 中间件获取 CSRF 令牌
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');

    //减少
    function decrementQuantity(button) {
        var input = button.nextElementSibling; // 获取按钮的下一个兄弟元素，即输入框
        var currentValue = parseInt(input.value, 10);
        var productId = button.getAttribute('data-product-id');


        if (!isNaN(currentValue) && currentValue > 1) {
            input.value = currentValue - 1;
            //发送一个请求让后端拿到这个ID：
            fetch('/cart/decquantity/', {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken, // 在这里添加 CSRF 令牌
            },
                body: JSON.stringify({
                    productId: productId,
                    number:input.value
                }),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Success:', data);
                    // 可以在这里处理后端的响应，比如更新前端的状态或显示消息
                })
                .catch(error => {
                    console.error('Error:', error);
                    // 可以在这里处理错误，比如显示一个错误消息给用户
                });

        } else if (!isNaN(currentValue) && currentValue <= 1) {
            input.value = 1; // 保持为最小值1
        }
         location.reload();
    }

    function incrementQuantity(button) {
        var input = button.previousElementSibling; // 获取按钮的上一个兄弟元素，即输入框
        var currentValue = parseInt(input.value, 10);
        var productId = button.getAttribute('data-product-id');

        if (!isNaN(currentValue)) {
            input.value = currentValue + 1;

             fetch('/cart/decquantity/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken, // 在这里添加 CSRF 令牌
                },
                body: JSON.stringify({
                    productId: productId,
                    number: input.value
                }),
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Success:', data);
                    // 可以在这里处理后端的响应，比如更新前端的状态或显示消息
                })
                .catch(error => {
                    console.error('Error:', error);
                    // 可以在这里处理错误，比如显示一个错误消息给用户
                });
        } else {
            input.value = 1; // 如果不是数字，则设置为0
        }
         location.reload();
    }
</script>
{% endblock %}